<?php 
	
	//判断从前台传递过来的数据是否为空
	if (!empty($_POST)) {
		//php连接数据库
		$connect=mysqli_connect('127.0.0.1','root','root','my_db');

		if (!$connect) {
			echo "<script>alert('连接数据库不成功');</script>";
		}

		//获取从前台传递过来的数据,用户的账号和密码(已经加密);
		$name=$_POST['username'];
		$pass=md5($_POST['password']);

		//设置从数据库获取的数据的编码
		mysqli_query($connect,'set names utf-8');

		//从数据库查询合法输入的用户信息
		$sql="select * from `admin` where `username`='$name' and `password`='$pass'";

		//执行数据库查询操作,得到的是结果集.不是符合条件的数据;
		$result=mysqli_query($connect,$sql);

		// print_r($result);

		//从结果集中取出最终数据
		$data=mysqli_fetch_assoc($result);
		// print_r($data);


		#如果从结果集取到了数据,则说明登录成功
		if (!empty($data)) {
			echo "<script>alert('登陆成功');location='index.php'</script>";

			//用户登录成功,并且记住密码框选中,将信息保存在cookie中
			if (!empty($_POST['check'])) {
				setcookie('username',$name,time()+3600*24);
				setcookie('password',$pass,time()+3600*24);

				//解决二次加密情况
				if (!empty($_COOKIE)) {
					$newpass=$_POST['password'];
					setcookie('newpass',$newpass,time()+3600*24);
				}
			}else{
				//清空cookie
				setcookie('username','',0);
				setcookie('password','',0);
			}

			//使用session之前要先开启session
			session_start();
			//用户登陆成功后将信息保存在session中,方便其他页面取用;
			$_SESSION['admin']=$data;
		}else{
			echo "<script>alert('用户名或密码错误');history.go(-1);</script>";
		}
	}

 ?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>登录页面</title>
	<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body>
	<div class="container">
		<div class="row">
			<div class="col-md-4">
				
			</div>
			<div class="col-md-4">
				<form action="" method="post">
		                           <div class="form-group">
			                    <label for="Name">用户名</label>
			                    	<input value="<?php echo !empty($_COOKIE['username'])?$_COOKIE['username']:''; ?>" placeholder="请输入用户名" class="form-control" type="text" name="username" id="Name">
		                           </div>
		                           <div class="form-group">
		                           	<label for="Password" >密码</label>
			                    	<input value="<?php echo !empty($_COOKIE['password'])? $_COOKIE['newpass']: ''; ?>" placeholder="请输入密码" class="form-control" type="text" name="password" id="Password">
		                           </div>
		                           <div class="checkbox">
		                           	<label for="Check">
		                           		<input <?php echo !empty($_COOKIE['username'])?'checked="checked"':' '; ?> id="Check" type="checkbox" name="check" value="1">记住密码
		                           	</label>
		                           </div>
		                           <button type="submit" class="btn btn-primary" >登录</button>
	                                </form>
			</div>
			<div class="col-md-4">
					
			</div>
		</div>
	</div>
</body>
</html>